
var WindowManager = Class.create();

WindowManager.prototype = {

  save_location: function(key,x,y,width,height) {
    var element = this.elements[key];
    if(!element) return false;
    params = "uid="+element.uid+"&x="+x+"&y="+y+"&width="+width+"&height="+height;
    new Ajax.Request("/create",
     { method: 'post',
       asynchronous: true,
       evalScripts: true,
       parameters: params
     });
    return false;
  },

  remake_one: function(element) {
    var xfocus = this;

    // get position from extended area
    element.extended.split('&').each( function(term) {
       parts = term.split('=');
       element[parts[0]] = parts[1];
     }
    );

    // if already present apply layout (move it)
    if(element.div) {
         element.div = xfocus.parametric_elem(
                            element.key,
                            element.title,
                            element.text,
                            element.x,
                            element.y,
                            element.width,
                            element.height
                            );
      return false;
    }

    // must load it for first time; i set a random position for new ones
    // xxx should respect the size supplied

    new Ajax.Request(element.link,
     { method: 'post',
       asynchronous: true,
       evalScripts: true,
       onComplete: function(r) {
         element.text = r.responseText;
         element.div = xfocus.parametric_elem(
                            element.key,
                            element.title,
                            element.text,
                            element.x,
                            element.y,
                            element.width,
                            element.height
                            );
         xfocus.elements[element.id].div = element.div;
       }
     });
    return false;
  },

  // find
  find_canonical_element: function(element) {
    element.key = this.usename + "_" + element.id;
    if(!element || !element.key) { 
      alert("no id " + element.description ); return;
    }
    return this.elements[element.key];
  },

  // general purpose handler for adding or modifying state
  insert_or_update: function(element) {
    element.key = this.usename + "_" + element.id;
    if(!element || !element.key) { 
      alert("no id " + element.description ); return;
    }
    var found = this.elements[element.key];
    if( found ) {
      found.extended = element.extended;
      element = found;
    } else {
      this.elements[element.key] = element;
    }
    return element;
  },

  // create
  callback_create: function(text) {
    this.callback_handler(text);
  },

  // server side ajax callback 
  callback_handler: function(text) {
    if(!text || text.length < 10) return;
    var results;
    try {
      results = eval('('+text+')');
    } catch(err) {
      return false;
    }
    if(!results) { 
      return false;
    }
    if(results.constructor == Array) {
      for(var i = results.length - 1; i >= 0; i-- ) {
        var element = results[i].attributes;
        //var temp = this.find_canonical_element(element);
        //if(this.latch_changed && temp.div == latch_changed) {
          //continue;
        //}
        element = this.insert_or_update(element);
        this.remake_one(element)
      }
      return false;
    } else {
      if( results.attributes ) {
        var element = results.attributes;
        var temp = this.find_canonical_element(element);
	//if(this.latch_changed && temp.div == latch_changed) {
	    //return false;
	//}
        element = this.insert_or_update(element);
        this.remake_one(element)
        return false;
      }
    }
    alert('bad data ' + text);
    return false;
  },

  // concat two things as a file paths
  concat: function(a,b) {
    if(b[0] == '/') b = b.substring(1);
    if(a[a.length-1] == '/') return a+b;
    return a+"/"+b;
  },

  // get url as a path
  path: function() {
    var i = location.href.indexOf('/',7);
	    domain = location.href.substring(7,i).split('.').reverse();
	    path = location.href.substring(i+1).split('/');
	    return "/"+Array.concat(domain,path).join('/');
  },

  // build just about anything on demand
  create: function(uid,params) {
    var xfocus = this;

    // if no uid is supplied then at least supply relative path meaning create as child of current url
    if(!uid || uid[0] != '/' ) {
      var path = this.path();
      if(uid) {
        uid = this.concat(path,uid);
      } else {
        uid = this.concat(path,"/");
      }
    }
    params = "uid="+uid+"&"+params
	
    // widgets accept a position that we can store in extended part of note
    if( params.indexOf("&x=") < 1 && params.indexOf("&width=" > 0)) {
      left = 0;
      top = 0;
      if( !left ) { left = this.cascadex; this.cascadex += 20; if( this.cascadex > 400 ) this.cascadex -= 398; }
      if( !top ) { top = this.cascadey; this.cascadey += 20; if( this.cascadey > 400 ) this.cascadey -= 398; }
      params += "&x="+left+"&y="+top
    }

    // submit to /create which is globally registered to handle this
    // possibly could submit to the current relative url?
    new Ajax.Request('/create',
     { method: 'post',
       asynchronous: true,
       evalScripts: true,
       parameters: params,
       onComplete: function(request){ xfocus.callback_create(request.responseText)}
     });
    return false;
  },

  findYPosition: function(obj) {
    // http://www.quirksmode.org/js/findpos.html
	    var curleft = curtop = 0;
	    if (obj.offsetParent) {
		      curleft = obj.offsetLeft
		      curtop = obj.offsetTop
		      while (obj = obj.offsetParent) {
			        curleft += obj.offsetLeft
			        curtop += obj.offsetTop
		      }
    	}
    	return curtop;
  },

  initialize: function() {
    var xfocus = this;
    var path = this.path();
    var tiny = document.getElementById("desk_start");
    if(tiny) { this.miny = xfocus.findYPosition(tiny) + 10; }
    // for now always force a palette item into the page
    this.create(".palette","title=palette&description=palette&link=/desk/palette.html&x=0&y=0&width=100&height=200");
    // show all once now
    new Ajax.Request('/query',
     { method: 'post',
       asynchronous: true,
       evalScripts: true,
       parameters: "uid="+path+"&order=desc&limit=100",
       onComplete: function(r) { xfocus.callback_handler(r.responseText); }
     });
    return false;
  }
}
